package com.ruoyi.classai.api;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.classai.domain.*;
import com.ruoyi.classai.domain.vo.courseplan.EwcCourseplanVo;
import com.ruoyi.classai.service.*;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.system.api.RemoteAiModelService;
import com.ruoyi.system.api.domain.AipptOutline;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import javax.validation.constraints.NotBlank;

@Slf4j
@RestController
@RequestMapping("/api")
public class AiInfo  extends BaseController {
    @Autowired
    private LearningStatisticsService learningStatisticsService;
    @Autowired
    private RemoteAiModelService remoteAiModelService;
    @Autowired
    private IEwcAiTemplateService  ewcAiTemplateService;
    @Autowired
    private IEwcCourseService ewcCourseService;
    @Autowired
    private IEwcCourseplanService courseplanService;
    @Operation(summary = "学情分析页面AI查询接口")
    @GetMapping("/getLearningStatisticsAiInfo")
    public AjaxResult getLearningStatisticsInfo(@NotBlank(message = "课程ID不能为空")String courseId,
                                                @NotBlank(message = "章节id不能为空")String chapterId,
                                                @NotBlank(message = "班级id不能为空")String classId){
        AjaxResult ajaxResult = learningStatisticsService.getLearningStatisticsInfo(courseId,chapterId,classId);
        //获取学习信息，并获取模板内容
        String msgTemplate = String.valueOf(ewcAiTemplateService.getById("learningStatisticsAiInfo"));
        EwcCourse courseServiceById = ewcCourseService.getById(courseId);
        msgTemplate = msgTemplate.replace("@course@",courseServiceById.getCourseName() );
        msgTemplate = msgTemplate.replace("@data@", ajaxResult.toString());
        log.info("msgTemplate:"+msgTemplate);
        String chat = remoteAiModelService.chat(msgTemplate, String.valueOf(UUID.randomUUID()));
        log.info("aiResult:"+chat);
        // 解析JSON字符串
        JSONObject jsonObject1 = new JSONObject(chat);

        // 提取小组建议和分组建议
        String groupSuggestion = jsonObject1.getStr("学习建议");
        String groupingSuggestion = jsonObject1.getStr("分组建议");
        Map  result = new HashMap<>();
        result.put("groupSuggestion", groupSuggestion);
         result.put("groupingSuggestion", groupingSuggestion);
        AjaxResult aiResult = AjaxResult.success(result);
        if (ajaxResult.isSuccess()){
            return aiResult;
        }
        return AjaxResult.error("查询失败");
    }

    @Operation(summary = "查询课程规划信息AI")
    @GetMapping("/getLessonPlanByIdAi")
    public AjaxResult getLessonPlanByIdAi(@NotBlank(message = "教学ID不能为空")String coursePlanId,
                                                 String grade,
                                                 String className,
                                                 String studentNum,
                                                 String classTime,
                                                 String teacherName,
                                                 String week,
                                                 String classHour,
                                                 String subjectMatter,
                                                 String learningGoal,
                                                 String teachingFocus,
                                                 String difficultPoints){

        EwcCourseplanVo lessonPlanById = courseplanService.getLessonPlanById(coursePlanId);
        List teachingTypeList =new ArrayList<>();
        if(lessonPlanById.getCourseplanTeachings()!= null){
            for ( EwcCourseplanTeaching aiTeaching : lessonPlanById.getCourseplanTeachings()){
                Integer teachingType = aiTeaching.getTeachingType();
                teachingTypeList.add(teachingType);
            }
        }else{
            lessonPlanById.setCourseplanTeachings(new ArrayList<>());
        }
        if(teachingTypeList.containsAll(Arrays.asList(0,1,2,3))){
            return AjaxResult.success(lessonPlanById);
        }
        //获取模板内容
        String msgTemplate = String.valueOf(ewcAiTemplateService.getById("LessonPlanAiInfo"));
        msgTemplate = msgTemplate.replace("@年级@",grade);
        msgTemplate = msgTemplate.replace("@班级@",className);
        msgTemplate = msgTemplate.replace("@人数@",studentNum);
        msgTemplate = msgTemplate.replace("@日期@",classTime);
        msgTemplate = msgTemplate.replace("@执教教师@",teacherName);
        msgTemplate = msgTemplate.replace("@周次@",week);
        msgTemplate = msgTemplate.replace("@课时@",classHour);
        msgTemplate = msgTemplate.replace("@课时主题@",subjectMatter);
        msgTemplate = msgTemplate.replace("@学习目标@",learningGoal);
        msgTemplate = msgTemplate.replace("@教学重点@",teachingFocus);
        msgTemplate = msgTemplate.replace("@教学难点@",difficultPoints);

        log.info("msgTemplate:"+msgTemplate);
        AipptOutline aipptOutline= new AipptOutline();
        aipptOutline.setMsg(msgTemplate);
        aipptOutline.setUserid(String.valueOf(UUID.randomUUID()));
        String chat = remoteAiModelService.chatPost(aipptOutline);
        log.info("aiResult:"+chat);
        // 解析JSON数据
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        CoursePlan coursePlan = gson.fromJson(chat, CoursePlan.class);
        Data coursePlanData = coursePlan.getData();

        // 1. 基础字段赋值（空值替换）
        if (lessonPlanById.getCoursePlanId() == null) {
            lessonPlanById.setCoursePlanId("");
        }
        if (lessonPlanById.getResourceSupport() == null) {
            lessonPlanById.setResourceSupport(coursePlanData.getResourceSupport());
        }
        if (lessonPlanById.getSecurityGuarantee() == null) {
            lessonPlanById.setSecurityGuarantee(coursePlanData.getSecurityGuarantee());
        }
        if (lessonPlanById.getFullCourse() == null) {
            lessonPlanById.setFullCourse(coursePlanData.getFullCourse());
        }
        if (lessonPlanById.getContentTheme() == null) {
            lessonPlanById.setContentTheme(coursePlanData.getContentTheme());
        }
        if (lessonPlanById.getPracticeIntensity()== null) {  // 假设原始字段默认值为0
            lessonPlanById.setPracticeIntensity(String.valueOf(coursePlanData.getPracticeIntensity()));
        }
        if (lessonPlanById.getClassroomReflection() == null) {
            lessonPlanById.setClassroomReflection(coursePlanData.getClassroomReflection());
        }

        // 2. 教学内容列表赋值（空值替换）
        List<CourseplanTeaching> aiTeachings = coursePlanData.getCourseplanTeachings();


        if (aiTeachings != null && !aiTeachings.isEmpty()) {
          //判断lessonPlanById的courseplanTeachings集合是否有teachingType为1的元素，没有的话直接将 aiTeachings的teachingType为1的元素赋给lessonPlanById
            //判断lessonPlanById的courseplanTeachings集合是否有teachingType为2的元素，没有的话直接将 aiTeachings的teachingType为2的元素赋给lessonPlanById
            //判断lessonPlanById的courseplanTeachings集合是否有teachingType为3的元素，没有的话直接将 aiTeachings的teachingType为3的元素赋给lessonPlanById
            //判断lessonPlanById的courseplanTeachings集合是否有teachingType为4的元素，没有的话直接将 aiTeachings的teachingType为4的元素赋给lessonPlanById
            for(CourseplanTeaching  aiTeaching :aiTeachings){
                if(!teachingTypeList.contains(aiTeaching.getTeachingType())){
                    EwcCourseplanTeaching ewcTeaching = new EwcCourseplanTeaching();
                    ewcTeaching.setTeachingContents(aiTeaching.getTeachingContents());
                    ewcTeaching.setTeachingType(Integer.valueOf(aiTeaching.getTeachingType()));
                    ewcTeaching.setTeacherActivity(aiTeaching.getTeacherActivity());
                    ewcTeaching.setStudentActivity(aiTeaching.getStudentActivity());
                    ewcTeaching.setTeachingDemand(aiTeaching.getTeachingDemand());
                    ewcTeaching.setOrganizeFormationName(String.valueOf(aiTeaching.getOrganizeFormationName()));
                    ewcTeaching.setMotionNumber(String.valueOf(aiTeaching.getMotionNumber()));
                    ewcTeaching.setMotionTime(aiTeaching.getMotionTime());
                    ewcTeaching.setMotionIntensity(String.valueOf(aiTeaching.getMotionIntensity()));
                    ewcTeaching.setId("");
                    ewcTeaching.setCoursePlanId("");
                    ewcTeaching.setOrganizeFormation("");
                    ewcTeaching.setSort(aiTeaching.getSort() != null && !aiTeaching.getSort().isEmpty()
                            ? Integer.parseInt(aiTeaching.getSort())
                            : 0);                    ewcTeaching.setUpdateTime(null);
                    ewcTeaching.setCreateTime(null);
                    lessonPlanById.getCourseplanTeachings().add(ewcTeaching);
                }
            }
        }

        return AjaxResult.success(lessonPlanById);
    }


}

// 定义数据模型类
class CoursePlan {
    private Data data;

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }
}

class Data {
    private String coursePlanId;
    private String resourceSupport;
    private String securityGuarantee;
    private String fullCourse;
    private String contentTheme;
    private String practiceIntensity;
    private String classroomReflection;
    private List<CourseplanTeaching> courseplanTeachings;

    public String getCoursePlanId() {
        return coursePlanId;
    }

    public void setCoursePlanId(String coursePlanId) {
        this.coursePlanId = coursePlanId;
    }

    // getters and setters
    public String getResourceSupport() {
        return resourceSupport;
    }

    public void setResourceSupport(String resourceSupport) {
        this.resourceSupport = resourceSupport;
    }

    public String getSecurityGuarantee() {
        return securityGuarantee;
    }

    public void setSecurityGuarantee(String securityGuarantee) {
        this.securityGuarantee = securityGuarantee;
    }

    public String getFullCourse() {
        return fullCourse;
    }

    public void setFullCourse(String fullCourse) {
        this.fullCourse = fullCourse;
    }

    public String getContentTheme() {
        return contentTheme;
    }

    public void setContentTheme(String contentTheme) {
        this.contentTheme = contentTheme;
    }

    public String getPracticeIntensity() {
        return practiceIntensity;
    }

    public void setPracticeIntensity(String practiceIntensity) {
        this.practiceIntensity = practiceIntensity;
    }

    public String getClassroomReflection() {
        return classroomReflection;
    }

    public void setClassroomReflection(String classroomReflection) {
        this.classroomReflection = classroomReflection;
    }

    public List<CourseplanTeaching> getCourseplanTeachings() {
        return courseplanTeachings;
    }

    public void setCourseplanTeachings(List<CourseplanTeaching> courseplanTeachings) {
        this.courseplanTeachings = courseplanTeachings;
    }
}

class CourseplanTeaching {
    private String id;
     private String coursePlanId;
    private String teachingContents;
    private String teachingType;
    private String teacherActivity;
    private String studentActivity;
    private String teachingDemand;
    private String organizeFormationName;
     private String organizeFormation;
    private String motionNumber;
    private String motionTime;
    private String motionIntensity;
    private String sort;
    private String createTime;
    private String updateTime;

    public String getOrganizeFormationName() {
        return organizeFormationName;
    }

    public void setOrganizeFormationName(String organizeFormationName) {
        this.organizeFormationName = organizeFormationName;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCoursePlanId() {
        return coursePlanId;
    }

    public void setCoursePlanId(String coursePlanId) {
        this.coursePlanId = coursePlanId;
    }

    public String getOrganizeFormation() {
        return organizeFormation;
    }

    public void setOrganizeFormation(String organizeFormation) {
        this.organizeFormation = organizeFormation;
    }

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(String updateTime) {
        this.updateTime = updateTime;
    }

    // getters and setters
    public String getTeachingContents() {
        return teachingContents;
    }

    public void setTeachingContents(String teachingContents) {
        this.teachingContents = teachingContents;
    }

    public String getTeachingType() {
        return teachingType;
    }

    public void setTeachingType(String teachingType) {
        this.teachingType = teachingType;
    }

    public String getTeacherActivity() {
        return teacherActivity;
    }

    public void setTeacherActivity(String teacherActivity) {
        this.teacherActivity = teacherActivity;
    }

    public String getStudentActivity() {
        return studentActivity;
    }

    public void setStudentActivity(String studentActivity) {
        this.studentActivity = studentActivity;
    }

    public String getTeachingDemand() {
        return teachingDemand;
    }

    public void setTeachingDemand(String teachingDemand) {
        this.teachingDemand = teachingDemand;
    }



    public String getMotionNumber() {
        return motionNumber;
    }

    public void setMotionNumber(String motionNumber) {
        this.motionNumber = motionNumber;
    }

    public String getMotionTime() {
        return motionTime;
    }

    public void setMotionTime(String motionTime) {
        this.motionTime = motionTime;
    }

    public String getMotionIntensity() {
        return motionIntensity;
    }

    public void setMotionIntensity(String motionIntensity) {
        this.motionIntensity = motionIntensity;
    }
}